package com.yj.audio_output_device_new.callback.impl;

import android.os.Handler;
import android.os.Looper;

import com.alibaba.fastjson.JSON;
import com.yj.audio_output_device_new.bean.EventBean;
import com.yj.audio_output_device_new.callback.Callback;
import com.yj.audio_output_device_new.enums.Event;
import com.yj.audio_output_device_new.util.log.Log;

import io.flutter.plugin.common.EventChannel;

public class CallbackImpl implements Callback {

    private static final String TAG = CallbackImpl.class.getName();

    private static Callback callback;
    public static Callback getInstance(){
        if(callback == null){
            synchronized (CallbackImpl.class){
                callback = new CallbackImpl();
            }
        }
        return callback;
    }

    private final Handler handler;
    private EventChannel.EventSink eventSink;
    private CallbackImpl(){
        this.handler = new Handler(Looper.getMainLooper());
    }

    @Override
    public void onClassicDeviceDisconnected() {
        if(checkEventSink()){
            return;
        }
        EventBean eventBean = new EventBean();
        eventBean.setName(Event.onClassicDeviceDisconnected.ordinal());
        send2Flutter(eventBean);
    }

    private void send2Flutter(EventBean eventBean){
        handler.post(()->{
            eventSink.success(JSON.toJSON(eventBean));
        });
    }

    private boolean checkEventSink(){
        if(eventSink == null) {
            Log.e(TAG, "eventSink is null");
            return true;
        }
        return false;
    }

    @Override
    public void setEventSink(EventChannel.EventSink eventSink) {
        this.eventSink = eventSink;
    }
}
